/*
 * Copyright (c) 2025 STMROS Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include "stmconn/stmconn_interface.hpp"
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>

// 串口通信实现类
class StmConnSerial : public stmconn::StmConnInterface {
public:
  using SharedPtr = std::shared_ptr<StmConnSerial>;
  
  // 构造函数
  StmConnSerial(const std::string & device, uint32_t baudrate = 115200);
  
  // 析构函数
  ~StmConnSerial();
  
  // 实现接口方法
  bool send_message(const stmconn::StmLinkMessage & msg) override;
  bool open() override;
  void close() override;
  bool is_open() const override;
  
private:
  // 串口参数
  std::string device_;     // 串口设备路径
  uint32_t baudrate_;      // 波特率
  int serial_fd_;          // 串口文件描述符
  
  // 线程和同步
  std::thread read_thread_;
  std::thread write_thread_;
  std::mutex mutex_;
  std::condition_variable cv_;
  bool stop_threads_;
  
  // 发送队列
  std::queue<stmconn::StmLinkMessage> send_queue_;
  
  // 内部方法
  void read_thread_func();
  void write_thread_func();
  bool configure_serial();
  
  // 简单的消息解析
  bool parse_message(const uint8_t * data, size_t len, stmconn::StmLinkMessage & msg);
};